package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.R;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.dto.DeviceData;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
@Slf4j
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    @Override
    public RoomVo getRoomById(Long id) {

        return roomMapper.getRoomById(id);
    }

    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
       //获取该楼层的所有房间及房间设备，床及床设备信息
        List<RoomVo> rooms = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        for (RoomVo room : rooms) {
            //找房间设备数据
            List<DeviceInfo> deviceVos = room.getDeviceVos();
            if (!CollectionUtils.isEmpty(deviceVos)){
                log.info("该房间存在设备，去redis获取最新的值");
                for (DeviceInfo deviceVo : deviceVos) {
                    //去redis获取最新的值
               setDeviceDate(deviceVo);
                }
            }
            //遍历房间的床
            List<BedVo> bedVoList = room.getBedVoList();
            if (CollectionUtils.isEmpty(bedVoList)){
                continue;
            }
            for (BedVo bedVo : bedVoList) {
                //遍历每张床，把床上所有的设备取出来，注意：一个床可能有多个设备
                List<DeviceInfo> bedVoDevices = bedVo.getDeviceVos();
                if (CollectionUtils.isEmpty(bedVoDevices)){
                    continue;
                }
                for (DeviceInfo bedVoDevice : bedVoDevices) {
                    //去redis获取最新的值
                    setDeviceDate(bedVoDevice);
                }
            }
        }

        return rooms;
    }

    private void setDeviceDate(DeviceInfo deviceInfo) {
        Object deviceNewData = redisTemplate.opsForHash().get("deviceData", deviceInfo.getIotId());
        if (deviceNewData == null){
            return;
        }
        try {
            String dataStr = deviceNewData.toString();
            // 处理被双引号包裹的JSON字符串
            if (dataStr.startsWith("\"") && dataStr.endsWith("\"")) {
                dataStr = dataStr.substring(1, dataStr.length() - 1);
                // 处理转义字符
                dataStr = dataStr.replace("\\\"", "\"");
            }
            if (!dataStr.startsWith("[")) {
                log.warn("设备数据格式不正确，不是JSON数组格式，设备ID: {}，数据: {}", deviceInfo.getIotId(), dataStr);
                return;
            }
            List<DeviceData> deviceDataList = JSONUtil.toList(JSONUtil.parseArray(dataStr), DeviceData.class);
            deviceInfo.setDeviceDataVos(deviceDataList);
        } catch (Exception e) {
            log.warn("解析设备数据失败，设备ID: {}，数据: {}", deviceInfo.getIotId(), deviceNewData, e);
        }
    }


}
